package com.calm.cthreadpool;

import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Create by Calm
 * on 2019/8/12
 */
public class CCachedThreadPool extends AppCompatActivity {
    private final static String TAG = CCachedThreadPool.class.getSimpleName();
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.cfixedthreadpool);
        findViewById(R.id.start).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startTheadPool();
            }
        });
    }
    private void startTheadPool(){
        //CachedThreadPool是一种线程数量不定的线程池，只有非核心线程，线程数量为无限大。
        //比较适合做一些大量的耗时较少的任务
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 10; i++){
            final int index = i;
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    Log.e(TAG,"CCachedThreadPool Start Run: 任务 = "+index+",线程 = "+Thread.currentThread().getName());
                    try {
                        Thread.sleep(2000);
                    }catch (InterruptedException e){

                    }
                }
            };
            executorService.execute(runnable);
        }
    }
}
